<template>
  <el-row class="form-inspect-point" type="flex" justify="center">
    <el-col>
      <el-form
        :class="{ 'is-edit':!!editForm.id }"
        label-width="120px"
        :model="editForm"
        :rules="editFormRules"
        ref="editForm"
        @submit.native.prevent
      >
        <input type="hidden" v-model="editForm.id" />
        <el-form-item label="点位名称：" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" placeholder="请输入点位名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="二维码编码：" prop="pointCode">
          <el-input
            :disabled="isEdit"
            v-model.trim="editForm.pointCode"
            auto-complete="off"
            clearable
            placeholder="不填，则由系统自动生成，支持字母、数字"
          ></el-input>
        </el-form-item>
        <el-form-item label="点位类别：" prop="pointTypeId">
          <el-select v-model="editForm.pointTypeId" filterable :disabled="isEdit">
            <el-option v-for="item in pointTypeList" :key="item.id" :label="item.pointTypeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isMuilUnitUser" label="所属单位：" prop="orgId">
          <el-select filterable @change="handleOrgChange" v-model="editForm.orgId" placeholder="请选择" :disabled="isEdit">
            <el-option
              v-for="item in orgOptions"
              :key="item.organizationId"
              :label="item.shortName"
              :value="item.organizationId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在建筑物：" prop="fbsId">
          <tree-select
            v-model="editForm.fbsId"
            filterable
            :data="buildList"
            :defaultProps="buildDefaultProps"
            :checkedKeys="defaultCheckedFbsId"
            :nodeKey="buildNodeKey"
            :nodeClickable="nodeClickable"
            :disabled="!editForm.orgId"
          ></tree-select>
        </el-form-item>
        <el-form-item label="具体地址：">
          <el-input v-model="editForm.address" auto-complete="off" clearable placeholder="请填写具体地址"></el-input>
        </el-form-item>
        <el-form-item label="安装位置照片：" :class="{ 'exist-files': qiniuData.fileList.length>0}">
          <el-upload
            :action="QINIUUPLOADURL"
            :multiple="true"
            ref="upload"
            list-type="picture-card"
            :data="qiniuData"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemovePic"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
            :on-preview="$imgPreview"
            :file-list="qiniuData.fileList"
            accept="image/gif, image/jpeg, image/jpg, image/bmp, image/png"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button round @click="closeDialog()">取消</el-button>
          <el-button type="primary" round @click="savePointType('editForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss">
.form-inspect-point {
  .exist-files {
    .el-upload {
      display: none;
    }
  }
}
</style>

<script>
import util from '@/utils/util'
import { qnToken } from '@/api/api'
import { getFbsTree } from '@/api/fbs'
import {
  addOrUpdateInspectPoint,
  getInspectPointTypeList,
} from '@/api/inspectx'
import TreeSelect from '@/libs/TreeSelect/Main'
import { mapState, mapGetters } from 'vuex'

export default {
  name: 'InspectPointForm',
  components: {
    TreeSelect,
  },
  props: {
    editInfo: {
      type: Object,
      required: false,
    },
    closeDialog: {
      type: Function,
      required: true,
    },
    pointTypeList: Array,
  },
  computed: {
    ...mapState(['orgOptions', 'userinfo']),
    ...mapGetters(['isMuilUnitUser', 'userOrgId', 'userOrgIds']),
    isEdit() {
      return !!this.editInfo.id
    },
  },
  data() {
    // 编码
    var checkCode = (rule, value, callback) => {
      var reg = /^[A-Za-z0-9]+$/g
      let { pointCode } = this.editForm
      if (!pointCode) return callback()
      if (!reg.test(pointCode)) {
        callback(new Error('只能输入字母、数字'))
      } else {
        callback()
      }
    }
    return {
      buildList: [],
      qiniuData: {
        //上传图片携带的参数
        token: '',
        key: '',
        fileList: [],
      },
      defaultImg: this.GLOBAL.defaultImg,
      util: util,
      // 建筑物
      buildDefaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      buildNodeKey: 'id',
      defaultCheckedFbsId: [],
      editForm: {
        id: '',
        orgId: '',
        address: '',
        name: '',
        picUrl: '',
        pointCode: '',
        pointTypeId: '',
        picUrl: '',
        fbsId: '',
      },
      editFormRules: {
        orgId: [
          { required: true, message: '请选择所属单位', trigger: 'change' },
        ],
        fbsId: [
          { required: true, message: '请选择所在建筑物', trigger: 'blur' },
        ],
        name: [{ required: true, message: '请输入点位名称', trigger: 'blur' }],
        pointTypeId: [
          { required: true, message: '请选择点位类别', trigger: 'blur' },
        ],
        pointCode: [
          { required: false, validator: checkCode, trigger: 'change' },
        ],
      },
    }
  },
  created() {
    if (!this.isMuilUnitUser) {
      this.editForm.orgId = this.userOrgId
    }
    let infoObj = this.editInfo
    if (infoObj.id) {
      //编辑
      this.editForm.id = infoObj.id
      this.editForm.orgId = infoObj.orgId
      this.editForm.address = infoObj.address
      this.editForm.name = infoObj.name
      this.editForm.pointCode = infoObj.pointCode
      //this.defaultCheckedFbsId = infoObj.fbsId.toString().split(',')
      //this.editForm.fbsId = infoObj.fbsId
      this.editForm.pointTypeId = infoObj.pointTypeId
      this.editForm.picUrl = infoObj.picUrl
      infoObj.picUrl
        ? $.each(infoObj.picUrl.split(','), (index, url) => {
            this.qiniuData.fileList.push({
              name: '现场图片' + index,
              url: url,
            })
          })
        : ''
    }
    // this.getTypeList()
    this.getData()
    this.getToken() //获取token
  },
  methods: {
    nodeClickable(data) {
      if (!data.nodes || data.nodes.length == 0) {
        return true
      } else {
        this.$message.warning('只能选择末级节点')
        return false
      }
    },
    handleOrgChange() {
      this.getData()
    },
    getData() {
      if (!this.editForm.orgId) return
      let that = this
      getFbsTree({
        organizationId: this.editForm.orgId,
      }).then((res) => {
        that.buildList = res.data.length === 0 ? [] : res.data
        /*
         * 多选建筑物结构树初始赋值问题
         */
        that.$nextTick(() => {
          if (that.editInfo.id) {
            //编辑
            that.defaultCheckedFbsId = that.editInfo.fbsId.toString().split(',')
            that.editForm.fbsId = that.editInfo.fbsId
          }
        })
      })
    },
    getTypeList() {
      getInspectPointTypeList({
        queryType: 0,
      }).then((data) => {
        this.pointTypeOptions = data
      })
    },
    getToken() {
      //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token = result.data
      })
    },
    beforeAvatarUpload: function (file) {
      //重命名和校验
      var fielLocal = file.name.split('.')
      var fielType = '.' + fielLocal[fielLocal.length - 1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_' + new Date().getTime() + fielType
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isJPG && !isPNG) {
        this.$message.error('图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('图片大小不能超过 20MB!')
        return false
      }
    },
    handleAvatarSuccess: function (res, file, fileList) {
      //上传成功
      this.qiniuData.fileList = fileList
    },
    handleRemovePic: function (file, fileList) {
      //删除成功
      this.qiniuData.fileList = fileList
    },
    handleError: function (res) {
      this.$message({
        message: '上传失败',
        duration: 2000,
        type: 'warning',
      })
    },
    savePointType(formName) {
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          let parames = that.editForm
          parames.picUrl = util.ilinkArrHandle
            .getqiniuPicUrlArr(this.qiniuData.fileList)
            .toString()
          parames.codeType = parames.pointCode ? 2 : 1
          if (!parames.id) {
            parames.createAccount = this.userinfo.accountName
          }
          parames.updateAccount = this.userinfo.accountName
          parames.pointTypeId = parames.pointTypeId || 1
          addOrUpdateInspectPoint(parames).then((res) => {
            if (res.status == 200) {
              that.$message({
                message: '保存成功！',
                type: 'success',
              })
              that.closeDialog(true)
            } else {
              this.$message.error(res.info)
            }
          })
        } else {
          return false
        }
      })
    },
  },
}
</script>